package problem581;

//581.最短无序连续子数组
//https://leetcode.cn/problems/shortest-unsorted-continuous-subarray/description/

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int n = nums.length;
        int l = 0, r = n-1;
        while(l < r && nums[l+1] >= nums[l]) {
            l++;
        }
        while(l < r && nums[r-1] <= nums[r]) {
            r--;
        }
        if(l == r) return 0;
        //获取 l ~ r 间的最大最小值
        int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
        for(int i = l; i<=r; i++) {
            max = Math.max(max, nums[i]);
            min = Math.min(min, nums[i]);
        }
        while(l-1 >= 0 && nums[l-1] > min) {
            l--;
        }
        while(r+1 < n && nums[r+1] < max) {
            r++;
        }
        return r-l+1;
    }
}